#include "project.h"
#include "usqlite.h"

int main(int argc, const char *argv[])
{
    if (argc < 2){
        ERR_LOG("请输入端口号");
    }
    
    //初始化创建tcp
    int s_fd = tcp_net_int(argv[1]);
    if (s_fd == -1){
        return -1;
    }

    /*消息队列初始化*/
	key_t my_key = ftok(MSGPATH,'a');
	if(-1 == my_key){
		close(s_fd);
        ERR_LOG("系统初始化失败");
	}
	msqid = msgget(my_key, IPC_CREAT | 0666);
	if(-1== msqid){
		close(s_fd);
        ERR_LOG("系统初始化失败");
	}

    /*初始化数据库*/
    if (sq_init() == -1){
        close(s_fd);
        exit(-1);
    }

    /*创建链表*/
	L = link_creat();
	if(NULL==L){
		close(s_fd);
		msgctl(msqid,IPC_RMID,NULL);
        ERR_LOG("系统初始化失败");
	}

    pthread_t tid = 0;
    /*创建处理检索下位机在线与否的线程*/
	pthread_create(&tid,NULL,login_thread,NULL);
	pthread_detach(tid);
    
    int acceptfd = 0;
    printf("服务器已启动，等待连接...\n");

    while (1)
    {
        // 连接
        acceptfd = accept(s_fd, NULL, NULL);
        if (acceptfd == -1){
            printf("连接失败...\n");
            continue;
        }
        printf("客户端[%d]连接成功\n", acceptfd);
        pthread_create(&tid, NULL, handl_thread, &acceptfd);
        pthread_detach(pthread_self());
    }
    // 关闭
    close(s_fd);

    return 0;
}